package com.tange.ai.iot.client.gnssa.configure

import android.app.AlarmManager
import android.app.PendingIntent
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.MenuItem
import android.view.View
import android.view.Window
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.preference.PreferenceFragmentCompat
import com.tange.ai.iot.client.gnssa.Constants
import com.tange.ai.iot.client.gnssa.R
import com.tange.ai.iot.client.gnssa.utils.SP
import com.tange.base.toolkit.StatusBarUtil
import com.tange.base.toolkit.StatusNavUtils
import com.tange.base.toolkit.Tips
import com.tange.base.toolkit.onClicked
import com.tange.base.ui.design.BasicDialogRequest

class AppSettingsActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setLightStatusBar(this, true)
        StatusNavUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_background))
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.settings_activity)
        if (savedInstanceState == null) {
            supportFragmentManager
                .beginTransaction()
                .replace(R.id.settings, SettingsFragment())
                .commit()
        }
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.title = "应用配置"
        supportActionBar?.hide()

        findViewById<View>(R.id.apply).onClicked { restartApplication() }

        findViewById<View>(R.id.egg_test).onClicked { fillTest() }
        findViewById<View>(R.id.egg_prod).onClicked { fillProd() }
        findViewById<View>(R.id.restore).onClicked { restoreConfigure() }

        val oldAppId = SP.getString(this@AppSettingsActivity, Constants.KEY_CUSTOM_APP_ID, "")
        val oldAppPkg = SP.getString(this@AppSettingsActivity, Constants.KEY_CUSTOM_APP_PKG, "")
        val oldAppEnv = SP.getString(this@AppSettingsActivity, Constants.KEY_CUSTOM_APP_ENV, "")
        if (TextUtils.isEmpty(oldAppId) && TextUtils.isEmpty(oldAppPkg) && TextUtils.isEmpty(oldAppEnv)) {
            window?.decorView?.postDelayed({ Tips.show("当前使用的是默认配置！") }, 500)
        }
    }

    private fun restoreConfigure() {
        SP.saveString(this@AppSettingsActivity, Constants.KEY_CUSTOM_APP_ID, "")
        SP.saveString(this@AppSettingsActivity, Constants.KEY_CUSTOM_APP_PKG, "")
        SP.saveString(this@AppSettingsActivity, Constants.KEY_CUSTOM_APP_ENV, "")
        window?.decorView?.postDelayed({ restartApplication() }, 500)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean =
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            window?.decorView?.postDelayed({ restartApplication() }, 500)
            true
        } else super.onKeyDown(keyCode, event)

    private fun fillProd() {
        BasicDialogRequest(this).apply {
            setMessage("确定使用 5920020（正式）？")
            setPositiveText("确定")
            setNegativeText("算了")
            setPositiveOnClicked {
                SP.saveString(this@AppSettingsActivity, Constants.KEY_CUSTOM_APP_ID, "5920020")
                SP.saveString(this@AppSettingsActivity, Constants.KEY_CUSTOM_APP_PKG, "com.tange365.icam365")
                SP.saveString(this@AppSettingsActivity, Constants.KEY_CUSTOM_APP_ENV, "0")
                window?.decorView?.postDelayed({ restartApplication() }, 500)
            }
            setNegativeOnClicked {
                dismiss()
            }
        }.show()
    }

    private fun fillTest() {
        BasicDialogRequest(this).apply {
            setMessage("确定使用 1553153（测试）？")
            setPositiveText("确定")
            setNegativeText("算了")
            setPositiveOnClicked {
                SP.saveString(this@AppSettingsActivity, Constants.KEY_CUSTOM_APP_ID, "1553153")
                SP.saveString(this@AppSettingsActivity, Constants.KEY_CUSTOM_APP_PKG, "com.tange365.icam365")
                SP.saveString(this@AppSettingsActivity, Constants.KEY_CUSTOM_APP_ENV, "2")
                window?.decorView?.postDelayed({ restartApplication() }, 500)
            }
            setNegativeOnClicked {
                dismiss()
            }
        }.show()
    }

    class SettingsFragment : PreferenceFragmentCompat() {
        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey)
        }
    }

    private fun restartApplication() {
        val intent = packageManager.getLaunchIntentForPackage(application.packageName)
        val restartIntent = PendingIntent.getActivity(applicationContext, 0, intent,
            PendingIntent.FLAG_IMMUTABLE)
        val mgr = getSystemService(ALARM_SERVICE) as AlarmManager
        mgr[AlarmManager.RTC, System.currentTimeMillis() + 500] = restartIntent // 500ms后重启应用
        System.exit(0)
    }
}

class TripleClickChecker {

    private val MAX_INTERVAL = 500L  // 最大点击间隔设定为500ms
    private var lastClickTime = 0L
    private var clickCount = 0

    // 检测是否是快速连击三次
    fun isTripleClick(): Boolean {
        // 当前点击时间
        val currentTime = System.currentTimeMillis()

        // 判断两次点击间的时间差
        if (currentTime - lastClickTime <= MAX_INTERVAL) {
            clickCount++  // 递增点击次数
            // 检查是否连击了三次
            if (clickCount == 1) {
                // 重置计数器
                clickCount = 0
                // 返回true表示成功连击三次
                return true
            }
        } else {
            // 超出时间间隔，重置计数器
            clickCount = 1
        }

        // 更新最后点击时间
        lastClickTime = currentTime
        return false
    }
}